import { messages, getToken, getQueryUrlParam } from "share/common";
import React from "react";
import { connect } from "react-redux";
import { Affix, message, Button, Modal, Icon } from "antd";
import menuRoute from "routes/menuRoute";
import ApproveBar from "components/template/approve-bar";
import financeAuditService from "containers/financial-management/finance-audit/finance-audit.service";
import baseService from "share/base.service";
import expenseReportService from "containers/expense-report/expense-report.service";
import borrowService from "containers/loan-billing/borrow-and-return.service";
import "styles/approve/request/request.scss";
import Condition from "components/condition";
import ApproveExpenseReportService from "containers/approve/expense-report/approve-expense-report.service";
import autoAuditService from "containers/finance-setting/auto-audit/auto-audit.service";
import approveService from 'containers/approve/approve.service';
import AuditNoticeModal from "containers/financial-management/new-finance-audit/components/audit-notice-modal";
const { If } = Condition;

class AuditApplicationDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      passLoading: false,
      rejectLoading: false,
      noticeLoading: false,
      printLoading: false,
      checkLoading: false,
      modalShow: false,
      paperReject: false,
      paperLoading: false,
      rejectReason: "",
      approvalTxtString: "",
      event: [],
      invoiceNumber: 0,
      failedInvoices: [],
      financeAuditList: menuRoute.getRouteItem("finance-audit"),
      certificateVisible: false,
      certificateLink: "",
      autoAuditLoading: false,
      hasAutoAudit: null,
      additionalItems: [],
      showAdditional: false,
      companyOIDs: [],
      enableManual: false, //是否开启人工审核时手动调用
      isNotice: false,
      hangUpLoading: false,
      noticeVisible: false
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.companyOid && typeof this.state.hasAutoAudit !== "boolean") {
      this.setState({
        failedInvoices: nextProps.failedInvoices,
        invoiceNumber: nextProps.failedInvoices
          ? nextProps.failedInvoices.length
          : 0,
      });
      Promise.all([
        nextProps.entityType === 1002 &&
          expenseReportService.canAutoAudit(nextProps.companyOid),
        expenseReportService.getPrintCertificate(
          nextProps.entityType === 1002
            ? "Exp_Report_Print_Doc"
            : "CA_PRINT_DOCUMENT"
        ),
        nextProps.entityType === 1002 &&
          ApproveExpenseReportService.isCounterSignEnable(
            nextProps.companyOid,
            nextProps.formOID,
            "enableAddSign",
            nextProps.user.userOID,
            nextProps.entityOID,
            1002
          ),
        autoAuditService.getAutoSetting(),
      ])
        .then((res) => {
          let params =
            nextProps.entityType === 1002
              ? {
                  showAdditional: res[2].data.enabled,
                  companyOIDs: res[2].data.approvalAddSignScope.companyOIDs,
                  enableManual: res[3].data.enableManual,
                }
              : {};
          if (res[0].data) {
            params.hasAutoAudit = res[0].data;
          }
          if (res[1].data) {
            params.certificateVisible = true;
            params.certificateLink = res[1].data.link;
          }
          this.setState(params);
        })
        .catch(() => {
          message.error(messages("financial-management.key566") /*系统异常*/);
        });
    }
  }

  //返回
  goBack = () => {
    const { tab } = this.props;
    localStorage.setItem('isBackFinance', true)
    this.context.router.push(
      this.state.financeAuditList.url.replace(
        ":tab",
        `${tab === "prending_audit" ? "prending_audit" : "audit_pass"}`
      )
    );
  };

  //别吐槽这里为啥用params1和params2这名字
  //因为传出来的参数根本不知道是啥，顺序都是乱的
  //我发现的时候竟然全项目已经通用了，之前竟然没人觉得很反人类？
  handleApprovePass = (value, params1, params2) => {
    let isHandle = value && typeof value !== "string";
    //这块代码传参写的稀烂，what's your problem ？？？
    //本来我以为只有后面俩参数不知道是啥，现在发现这三个参数都不知道是啥
    //后面俩参数不一样就罢了，第一个参数竟然还有可能是onClick传过来的event????
    //用state传参数是怎么想出来的方法，明明一个确认用Modal.confirm就能搞定，onOk直接参数固定哪来这么多判断
    //实现功能就算完事了？维护性不谈了？
    //这种结构后面跑tdd之类的东西根本没办法
    //以前还对ts的强类型嗤之以鼻觉得多此一举，现在看来在团队里使用真是无比正确
    //我不打算改这里，就让这稀烂的代码留在这里起警示作用
    //我佛了
    let { approvalTxtString, event, additionalItems } = this.state;
    const { entityOID, entityType, approvalHistory = [] } = this.props;
    let events,
      additionalUsers = [];
    if (entityType === 1002) {
      events = params1;
      additionalUsers = params2;
    } else {
      additionalUsers = params1;
    }
    additionalUsers = isHandle ? additionalItems : additionalUsers || [];
    let preApproveOIDs = [];
    let additionalHaveApprovedNames = []; //加签人中已审批的用户名
    approvalHistory.map((item) => {
      item.operation === 2001 && preApproveOIDs.push(item.operatorOID);
    });
    let additionalOIDs = additionalUsers.map((item) => item.userOID);
    additionalOIDs.map((OID, index) => {
      if (preApproveOIDs.indexOf(OID) > -1) {
        additionalHaveApprovedNames.push(additionalUsers[index].fullName);
      }
    });
    event = event || [];
    value = value ? (isHandle ? approvalTxtString : value) : approvalTxtString;
    events = events ? (isHandle ? event : events) : event;
    let ids = [];
    events.map((item) => {
      ids.push(item.id);
    });
    let params = {
      approvalTxt: value ? value.trim() : value,
      entities: [
        {
          entityOID,
          entityType,
          countersignApproverOIDs: additionalOIDs,
        },
      ],
      conditionIds: ids,
    };
    
    if (this.state.isNotice) {
      // 通知按钮进来
      //https://pmo.mcd.com.cn/jira/browse/TES-2262
      if (this.props.reportInvoiceApprovalReqDTOList) {
        if (
          this.props.reportInvoiceApprovalReqDTOList.find((item) => {
            return String(item.approvalStatus) === "1002";
          })
        ) {
          message.error("费用行审核状态含驳回，请对整单驳回。");
          return;
        }
  
        params.entities[0].reportInvoiceApprovalReqDTOList = this.props.reportInvoiceApprovalReqDTOList;
      }
    } else {
      // 通过按钮进来
      // https://pmo.mcd.com.cn/jira/browse/TES-786
      if (this.props.reportInvoiceApprovalReqDTOList) {
        if (
          this.props.reportInvoiceApprovalReqDTOList.find((item) => {
            return String(item.approvalStatus) === "1002";
          })
        ) {
          message.error("费用行审核状态含驳回，请对整单驳回。");
          return;
        }
        if (
          this.props.reportInvoiceApprovalReqDTOList.find((item) => {
            return String(item.approvalStatus) === "1003";
          })
        ) {
          message.error("费用行审核状态含通知，请对整单通知。");
          return;
        }
  
        params.entities[0].reportInvoiceApprovalReqDTOList = this.props.reportInvoiceApprovalReqDTOList;
      }
    }
    if (additionalHaveApprovedNames.length) {
      Modal.confirm({
        title: `${additionalHaveApprovedNames.join("、")} ${messages(
          "approve.key58" /*已经审批通过，是否继续*/
        )}？`,
        onOk: () => this.fetchAuditPass(params),
      });
    } else {
      this.fetchAuditPass(params);
    }
  };

  fetchAuditPass = (params) => {
    // 判断是否是通知按钮的点击
    if (this.state.isNotice) {
      params.inform = true;
    }
    this.setState({ passLoading: true });
    financeAuditService
      .auditPass(params)
      .then((res) => {
        const { entityOID } = this.props;
        if (res.status === 200 && res.data.failNum === 0) {
          message.success(messages("common.operate.success") /*操作成功*/);
          this.setState({ passLoading: false });
          this.goBack();
        } else {
          this.setState({ passLoading: false });
          if (res.data.failReason && res.data.failReason[entityOID]) {
            message.error(res.data.failReason[entityOID]); //'的报销单审核失败'
            return !1;
          }
          message.error(messages("common.operate.filed") /*操作失败*/);
        }
      })
      .catch((e) => {
        this.setState({ passLoading: false });
        e.response.data.message
          ? message.error(
              `${messages("common.operate.filed")}，${e.response.data.message}`
            )
          : message.error(messages("common.operate.filed") /*操作失败*/);
      });
  };

  //value
  invoiceNumberPass = (value, params1, params2) => {
    const { entityType, invoiceEnabled } = this.props;
    let event = entityType === 1002 ? params1 : params2;
    let additionalItems = entityType === 1002 ? params2 : params1;
    this.setState({ approvalTxtString: value, event: event, additionalItems });
    const { invoiceNumber } = this.state;
    invoiceNumber !== 0 && invoiceEnabled
      ? this.setState({ modalShow: true })
      : this.handleApprovePass(value, params1, params2);
  };

  handleApproveReject = (value, event) => {
    this.setState(
      { rejectLoading: true, rejectReason: value, event: event },
      () => {
        if (
          this.checkFunctionProfiles(
            "finance.review.receive.required",
            true,
            false
          )
        ) {
          this.setState({ paperReject: true });
        } else {
          this.handlePaperReject(false);
        }
      }
    );
  };

  handlePaperReject = (isPaper, modal = false) => {
    modal && this.setState({ paperLoading: true });
    const { entityOID, entityType } = this.props;
    const { event } = this.state;
    let ids = [];
    event.map((item) => {
      ids.push(item.id);
    });
    let params = {
      approvalTxt: this.state.rejectReason,
      entities: [
        {
          entityOID,
          entityType,
        },
      ],
      conditionIds: ids,
      needChargeBack: isPaper,
    };

    // https://pmo.mcd.com.cn/jira/browse/TES-786
    if (this.props.reportInvoiceApprovalReqDTOList) {
      if (
        !this.props.reportInvoiceApprovalReqDTOList.find((item) => {
          // https://pmo.mcd.com.cn/jira/browse/TES-2091
          return String(item.approvalStatus) === "1002";
        })
      ) {
        // https://pmo.mcd.com.cn/jira/browse/TES-1549
        message.error("费用行审核状态无驳回，无法驳回。");
        this.setState({ rejectLoading: false });
        return;
      }
      params.entities[0].reportInvoiceApprovalReqDTOList = this.props.reportInvoiceApprovalReqDTOList;
    }
    financeAuditService
      .auditReject(params)
      .then((res) => {
        if (res.status === 200 && res.data.failNum === 0) {
          message.success(messages("common.operate.success") /*操作成功*/);
          this.setState({ rejectLoading: false });
          this.goBack();
        } else {
          this.setState({ rejectLoading: false });
          modal && this.setState({ paperReject: false, paperLoading: false });
          let errorMessage = res.data.failReason[params.entities[0].entityOID];
          message.error(errorMessage);
        }
      })
      .catch((e) => {
        this.setState({ rejectLoading: false });
        modal && this.setState({ paperReject: false, paperLoading: false });
        message.error(messages("common.operate.filed") /*操作失败*/);
      });
  };

  handleAuditNotice = (value) => {
    const { entityOID, entityType } = this.props;
    let params = {
      entityOID,
      entityType,
      notice: value,
    };
    this.setState({ noticeLoading: true });
    financeAuditService
      .noticeApplication(params)
      .then((res) => {
        if (res.status === 200) {
          message.success(messages("common.operate.success") /*操作成功*/);
          this.setState({ noticeLoading: false });
          this.goBack();
        }
      })
      .catch((e) => {
        this.setState({ noticeLoading: false });
        // message.error(messages("common.operate.filed") /*操作失败*/);
        message.error(e.response.data.message)
      });
  };

  handlePrint = () => {
    const { entityOID } = this.props;
    this.setState({ printLoading: true });
    if (this.props.entityType === 1002) {
      baseService.printExpense(entityOID).then((res) => {
        this.setState({ printLoading: false });
        window.open(res.data.link, "_blank");
      });
    } else {
      borrowService.printLoanApplication(entityOID).then((res) => {
        this.setState({ printLoading: false });
        window.open(res.data.link, "_blank");
      });
    }
  };

  handleAuditCheck = () => {
    const { failedInvoices } = this.state;
    this.setState({ checkLoading: true });
    expenseReportService.recheckInvoice(failedInvoices).then((res) => {
      if (res.data.failedCount === 0) {
        this.setState({ invoiceNumber: 0, failedInvoices: [] });
        message.success(
          messages("financial-management.key184" /*发票查验成功*/)
        );
      } else {
        this.setState({
          invoiceNumber: res.data.failedCount,
          failedInvoices: res.data.failedList,
        });
        message.warn(
          messages("financial-management.key185" /*有查验失败的发票信息*/)
        );
      }
      if (res.data.successList.length > 0) {
        this.props.afterClose(true);
      }
      this.setState({ checkLoading: false });
    });
  };

  closeModal = () => {
    this.setState({ modalShow: false });
  };

  handleAutoAudit = () => {
    const { entityOID, entityType } = this.props;
    let params = {
      entityOid: entityOID,
      auditType: entityType === 1002 ? 1001 : 1002,
    };
    this.setState({ autoAuditLoading: true });
    expenseReportService
      .autoAudit(params)
      .then((res) => {
        this.setState({ autoAuditLoading: false });
        if (res.data.auto) {
          message.success(messages("common.operate.success") /*操作成功*/);
          this.props.afterClose(true);
        } else {
          message.error(res.data.content);
        }
      })
      .catch((e) => {
        this.setState({ autoAuditLoading: false });
        message.error(e.response.data.message);
      });
  };

  //打印凭证
  handlePrintCertificate = () => {
    const { businessCode, parentBusinessCode, company } = this.props;
    let { certificateLink } = this.state;
    certificateLink += `&access_token=${JSON.parse(getToken()).access_token}`;
    let state = `businessCode=${businessCode}&companyOID=${company.companyOID}`;
    parentBusinessCode &&
      (state += `&parentBusinessCode=${parentBusinessCode}`);
    certificateLink += `&state=${btoa(state)}`;
    window.open(certificateLink, "_blank");
  };

  handleApproveNotice = (value, params1, params2) => {
    const { entityType, invoiceEnabled } = this.props;
    let event = entityType === 1002 ? params1 : params2;
    let additionalItems = entityType === 1002 ? params2 : params1;
    this.setState({ approvalTxtString: value, event: event, additionalItems, isNotice: true }, () => {
      const { invoiceNumber } = this.state;
      invoiceNumber !== 0 && invoiceEnabled
        ? this.setState({ modalShow: true })
        : this.handleApprovePass(value, params1, params2);
    });
  };

  // 单据暂挂显示弹窗
  handleApproveHangUp = () => {
    // let params = {
    //   entities: [{
    //     approverOID: this.props.user.userOID,
    //     entityOID: this.props.entityOID,
    //     entityType: this.props.entityType,
    //   }]
    // };
    // this.setState({ hangUpLoading: true });
    // approveService.handleEntityHangUp(params)
    //   .then(res => {
    //     const { failNum, failReason } = res.data;
    //     if (failNum === 0) {
    //       message.success(messages('common.operate.success'));
    //       this.goBack();
    //     } else {
    //       message.error(
    //         `${messages('common.operate.filed')}，${failReason[this.state.info.applicationOID]}`
    //       );
    //     }
    //   })
    //   .catch(e => {
    //     message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
    //   })
    //   .finally(() => {
    //     this.setState({ hangUpLoading: false });
    //   });
    this.setState({ noticeVisible: true })
  }

  render() {
    const {
      passLoading,
      rejectLoading,
      noticeLoading,
      printLoading,
      financeAuditList,
      invoiceNumber,
      checkLoading,
      modalShow,
      paperReject,
      paperLoading,
      autoAuditLoading,
      hasAutoAudit,
      certificateVisible,
      showAdditional,
      companyOIDs,
      enableManual,
      hangUpLoading,
      noticeVisible
    } = this.state;
    const {
      profile,
      status,
      applicantOID,
      tab,
      entityType,
      businessCode,
      invoiceEnabled,
      isAuditInApproveStatus,
      entityOID,
      user,
      customFormPropertyMap,
      approvalChains,
      info
    } = this.props;
    let moreButtons = [];
    // moreButtons.push("noticeBtn");
    ((!isAuditInApproveStatus && hasAutoAudit) || enableManual) &&
      moreButtons.push("autoAudit");
    invoiceNumber > 0 && invoiceEnabled && moreButtons.push("auditCheck");
    certificateVisible && moreButtons.push("print-certificate");
    isAuditInApproveStatus && showAdditional && moreButtons.push("additional");
    // moreButtons.push('hangUp');
    console.log("status", status)
    console.log("moreButtons", moreButtons)
    let showNotice = this.props.reportInvoiceApprovalReqDTOList ? true : false;
    return this.checkNewAuth() &&
      (status === 1003 || isAuditInApproveStatus) &&
      tab === "prending_audit" &&
      !(profile["er.disabled"] && 1002 === this.props.entityType) ? (
      <Affix offsetBottom={0} className="bottom-bar bottom-bar-approve">
        <ApproveBar
          needReason={false}
          backUrl={financeAuditList.url.replace(":tab", "prending_audit")}
          allLoading={
            passLoading ||
            rejectLoading ||
            noticeLoading ||
            printLoading ||
            autoAuditLoading ||
            checkLoading ||
            hangUpLoading
          }
          moreButtons={moreButtons}
          signCompanyOIDs={companyOIDs}
          handleApprovePass={this.invoiceNumberPass}
          handleApproveReject={this.handleApproveReject}
          handleAuditNotice={this.handleAuditNotice}
          handleAuditPrint={this.handlePrint}
          handleAutoAudit={this.handleAutoAudit}
          handleApproveTransfer={this.goBack}
          handleApproveAdditional={this.goBack}
          invoiceNumber={invoiceNumber}
          needHonest={entityType === 1002}
          applicantOID={applicantOID}
          businessCode={businessCode}
          handleAuditCheck={this.handleAuditCheck}
          handlePrintCertificate={this.handlePrintCertificate}
          entities={{
            approverOID: user.userOID, //多级审核中chain上的第一个审批人不一定是当前审批人，暂无代理的情况下先取登录人oid
            entityOID: entityOID,
            entityType: entityType,
          }}
          audit
          customFormPropertyMap={customFormPropertyMap}
          showNotice={showNotice}
          handleApproveNotice={this.handleApproveNotice}
          handleApproveHangUp={this.handleApproveHangUp}
          showHandUp={(status === 1002 && ((approvalChains && approvalChains[0] && approvalChains[0].brmsRemark && approvalChains[0].brmsRemark === '财务预审') || info.receiveStatus)) || status === 1010 ? true : false}
        />
        <AuditNoticeModal
          visible={noticeVisible}
          entityOID={entityOID}
          entityType={entityType}
          // reason={auditReason}
          close={closePage => this.setState({ noticeVisible: false }, () => closePage && this.goBack(true))}
        />
        <Modal
          footer={
            <div>
              <Button onClick={this.closeModal}>
                {messages("common.cancel") /* 取消 */}
              </Button>
              <Button
                onClick={() => {
                  this.setState({ modalShow: false });
                  this.handleAuditCheck();
                }}
              >
                {messages("common.invoiceNumber", { total: invoiceNumber })}
              </Button>
              <Button
                onClick={this.handleApprovePass}
                type="primary"
                loading={passLoading}
              >
                {messages("financial-management.key229") /*审核通过*/}
              </Button>
            </div>
          }
          onCancel={this.closeModal}
          confirmLoading={passLoading}
          visible={modalShow}
          closable={false}
        >
          <div>
            <Icon
              type="exclamation-circle"
              style={{ color: "#F7C243", fontSize: "30", float: "left" }}
            />
            <span
              style={{ lineHeight: "30px", fontSize: "20", marginLeft: "10px" }}
            >
              {
                messages(
                  "financial-management.key954"
                ) /*有未查验或查验失败的发票信息*/
              }
            </span>
            <div
              style={{
                marginLeft: "40px",
                fontSize: "16px",
                color: "red",
                lineHeight: "30px",
              }}
            >
              {messages("financial-management.key187" /*是否仍然审核通过*/)}
            </div>
          </div>
        </Modal>
        <Modal
          onCancel={() => {
            this.setState({ paperReject: false, rejectLoading: false });
          }}
          footer={
            <div>
              <Button
                type={"primary"}
                onClick={() => this.handlePaperReject(true, true)}
                loading={paperLoading}
                className={"okButton"}
              >
                {messages("financial-management.key188" /*驳回并退单*/)}
              </Button>
              <Button
                onClick={() => this.handlePaperReject(false, true)}
                loading={paperLoading}
                className={"cancelButton"}
              >
                {messages("financial-management.key189" /*驳回*/)}
              </Button>
            </div>
          }
          width={350}
          className={"paper-modal"}
          visible={paperReject}
          closable={true}
        >
          <div style={{ marginTop: "10px" }}>
            <Icon
              type="exclamation-circle"
              style={{ color: "#F7C243", fontSize: "25", float: "left" }}
            />
            <span
              style={{ lineHeight: "25px", fontSize: "16", marginLeft: "10px" }}
            >
              {messages(
                "financial-management.key190" /*是否需要退回纸质单据？*/
              )}
            </span>
          </div>
        </Modal>
      </Affix>
    ) : (
      <Affix offsetBottom={0} className="bottom-bar">
        <If value={certificateVisible}>
          <Button
            type="primary"
            style={{ marginRight: 10 }}
            onClick={this.handlePrintCertificate}
          >
            {messages("financial-management.key767") /*打印凭证*/}
          </Button>
        </If>
        <Button className="back-btn" onClick={this.goBack}>
          {messages("common.back") /*返回*/}
        </Button>
      </Affix>
    );
  }
}

AuditApplicationDetail.propTypes = {
  entityOID: React.PropTypes.string,
  entityType: React.PropTypes.number,
  status: React.PropTypes.number, //单据状态
  afterClose: React.PropTypes.func,
  applicantOID: React.PropTypes.string,
  tab: React.PropTypes.string,
  companyOid: React.PropTypes.string,
  businessCode: React.PropTypes.string,
  parentBusinessCode: React.PropTypes.string,
};

AuditApplicationDetail.defaultProps = {
  afterClose: () => {},
};

AuditApplicationDetail.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
  };
}

export default connect(mapStateToProps)(AuditApplicationDetail);
